# -*- coding: utf-8 -*-
# @name             : 用例文件模板
# @author           : OneYoung
# @create           : 2024/07/18
# @version          : v1.0
# @desc             : 根据模板内容自动生成用例文件

import json
import time
from typing import Any


def creat_case_model(
        case_name: str,
        class_name: str,
        api_url: str,
        def_name: str,
        params_data: Any,
        body_data: Any,
        method: str,
        p_format: str
):
    """
    创建用例模板

    :param case_name: 用例名称
    :param class_name: 用例方法名称
    :param api_url: 用例接口地址
    :param def_name: 用例名称
    :param params_data: params入参
    :param body_data: body入参
    :param method: 请求方法
    :param p_format: 入参模式：params/body/params_body
    """
    inf_import = f'''# -*- coding: utf-8 -*-
# @name             : 用例信息
# @author           : tester
# @create           : {time.strftime("%Y/%m/%d")}
# @version          : v1.0
# @desc             : {case_name}

from core.unit_case import *
'''
    className = '''

# ''' + case_name + '''
class ''' + class_name + '''(MyUnit):'''
    url_info = '''
    url = "''' + api_url + '''"'''
    config = '''

    # @unittest.skip("skip this case.")'''
    defName = '''
    def ''' + def_name + '''_normal(self):
        """''' + case_name + '''-正确传参"""
        logger.info("开始执行用例.")'''

    if params_data:
        params = '''
        # Params请求参数
        params_data = ''' + json.dumps(params_data, indent=12, ensure_ascii=False)
    else:
        params = ''
    if body_data:
        body = '''
        # Body请求参数
        body_data = ''' + json.dumps(body_data, indent=12, ensure_ascii=False)
    else:
        body = ''
    # 请求数据
    request_data = '''
        '''
    if params or body:
        request_data = '''
        ''' + params + '''''' + body + '''
        '''

    if p_format == "params":
        req_inf = '''
        self.http.set_params(params_data)'''
    elif p_format == "body":
        req_inf = '''
        self.http.set_json(body_data)'''
    elif p_format == "params_body":
        req_inf = '''
        self.http.set_params(params_data)
        self.http.set_json(body_data)'''
    else:
        req_inf = ''
    # 处理token
    token = '''
        # 获取信息
        token = self.auth.get()  # 获取授权token'''
    add_token = '''
        self.http.add_token(token)'''

    requestData = token + request_data + '''
        # 调用请求
        self.http.set_url(self.url)''' + req_inf + add_token
    method_inf = '''
        response = self.http.''' + method + '''()'''
    assert_inf = '''

        # 断言
        assertion = CustomAssert(response)  # 断言服务
        assertion.response_normal()  # 判断response是否正常返回
        assertion.status_code_equal()  # 状态码是否为预期值，默认200
        assertion.code_equal()  # 错误状态码是否为预期值，默认200

        # 用例执行结束
        logger.info("用例执行完成.")
    '''
    main_inf = '''

if __name__ == '__main__':
    unittest.main()
'''
    return inf_import, className, url_info, config, defName, requestData, method_inf, assert_inf, main_inf
